<template>
    <form onsubmit="return false">
      <van-cell-group :border="border">
        <van-field 
          v-model="phone" 
          @focus="mobileColor = true"
          @blur="mobileColor = false"
          :class="mobileColor ? 'active' : ''"
          clearable 
          type="tel" 
          maxlength="11" 
          placeholder="请输入手机号码" 
          autocomplete="username"
        >
          <van-icon 
            slot="left-icon" 
            class-prefix="ucai-icon" 
            name="shouji" 
            :color="mobileColor ? '#444' : '#999'"/>
        </van-field>
        <van-field 
          v-if="role >= 1"
          v-show="!loginBySms"
          v-model="password" 
          @focus="passwordColor = true"
          @blur="passwordColor = false"
          :class="passwordColor ? 'active' : ''"
          clearable 
          type="password" 
          placeholder="请输入密码" 
          autocomplete="current-password"
        >
          <van-icon 
            slot="left-icon"
            class-prefix="ucai-icon" 
            name="mima" 
            :color="passwordColor ? '#444' : '#999'"/>
        </van-field>
      
        <van-field
          v-if="role <= 1"
          v-show="loginBySms"
          v-model="captcha"
          @focus="codeColor = true"
          @blur="codeColor = false"
          :class="codeColor ? 'active' : ''"
          center
          clearable
          type="tel" 
          maxlength="6" 
          placeholder="请输入短信验证码"
        >
          <van-icon 
            slot="left-icon" 
            class-prefix="ucai-icon" 
            name="yanzhengma" 
            :color="codeColor ? '#444' : '#999'"
          />
          <sms-wrap slot="button" :phone="phone" ref="smsSend" />
        </van-field>
      </van-cell-group>

      <van-button 
        type="primary" 
        class="mg-top-xxl font-lg" 
        block 
        :disabled="!phone" 
        @click="login"
      >登&emsp;录</van-button>

      <van-row v-if="role == 1" type="flex" justify="space-between">
        <van-col span="12" v-show="!loginBySms" @click="changeLoginType">手机动态密码登录</van-col>
        <van-col span="12" v-show="loginBySms" @click="changeLoginType">账号密码登录</van-col>
        <van-col 
          span="6" 
          @click="$goPage('forgetPwd')" 
          class="text-right"
           v-show="!loginBySms"
        >修改密码</van-col>
        <van-col 
          span="6" 
          @click="$goPage('registe')" 
          class="text-right" 
          v-show="role == 1"
        >注册</van-col>
      </van-row>

    </form>
</template>

<script>
  import { mobileReg } from '@utils/regexp';
  import { login } from '@/api/modules/user';
  import { getConfig } from '@/api/modules/index';
  import SendSms from '@cmpt_com/sms';
  import { COMPANY_ARR } from '@data/dic/constant';
  import { 
    getSignInByKey,
    setSignIn,
    getUserData, 
    getStorageOpenid, } from '@utils/storage_base_config'
  import { Field, CellGroup, Button, Icon, Row, Col, Toast } from 'vant';
  import {
    getErrInfo,
  } from "@api/http"
  export default {
    name: 'login-request',
    props: {
      role: {
        type: String,
        default: '1'
      },
      isPopup: Boolean
    },
    data(){
        return {
          phone: this.role !== '2' ? getSignInByKey('account') : '',
          password: '',
          captcha: '',
          openid: getStorageOpenid(),
          once_str: '',
          mobileColor: false,
          passwordColor: false,
          codeColor: false,
          loginBySms: this.role === '0',
          border: false,
          noSms: true,
        }
    },
    components:{
      [Field.name]: Field,
      [CellGroup.name]: CellGroup,
      [Button.name]: Button,
      [Icon.name]: Icon,
      [Row.name]: Row,
      [Col.name]: Col,
      [SendSms.name]: SendSms,
    },
    created() {
      this.getWxInfo()
    },
    computed: {
      verify: function () {
          if(!this.phone){
              return {flag: true, msg: '请填写手机号码'};
          }else if(!mobileReg.test(this.phone)){
              return {flag: true, msg: '手机号码格式不正确'};
          }else if(mobileReg.test(this.phone)) {
            this.noSms = false;
          }
          if(this.$refs.smsSend){
            if(!this.$refs.smsSend.once_str && this.loginBySms){
              return {flag: true, msg: '请重新获取验证码'}
            }
          }
          if(!this.captcha && this.loginBySms){
              return {flag: true, msg: '请填写验证码'};
          }
          if(!this.password && !this.loginBySms){
              return {flag: true, msg: '请输入密码'};
          }
          return {flag: true, msg: 'ok'};
      }
    },
    methods:{
      // 微信登录
      getWxInfo() {
        if (!this.$is_from_wx)
          return
        if(this.openid){
          this.wxLogin(this.openid)
          return
        }
        require.ensure(['@utils/wechat'], (require) => {
          const wechat = require('@utils/wechat')['default']
          const code = this.$getUrlParam('code')
          code ? wechat.getOpenid(code).then(res => {
            const openid = (res.data || {}).openid
            console.log('【wechat.getOpenid then】', openid)
            if(!openid)
              return
            this.openid = openid
            this.wxLogin(openid)
          }) : wechat.getCode()
        }, 'wechat')
      },
      // 微信 openid 登录
      async wxLogin(openid) {
        login({
          openid: openid,
          kind: Number(this.role),
        }).then(res => {
          debugger
          setSignIn({
            ...res.data,
            role: this.role,
          })
          // 获取用户信息。强制刷新缓存。
          getUserData(true).finally(() => {
            this.afterLogin(res)
          })
        }).catch(err => {
          debugger
        })
      },
      changeLoginType (e) {
        this.loginBySms = !this.loginBySms
        this.loginBySms ? (this.password = '') : (this.captcha = '')
      },
      // 跳转地址
      getRedirect(page, params) {
        let redirect = this.$getUrlParam('redirect')
        params = params || {}
        page = page || 'profile'
        if(redirect){
          redirect = decodeURIComponent(redirect)
          page = redirect.split('?')[0]
          redirect = redirect.split('?')[1]
          redirect = redirect ? redirect.split('&') : []
          redirect && redirect.forEach(item => {
            params[item.split('=')[0]] = item.split('=')[1]
          })
        }
        this.$goPage(page, params, true)
      },
      async login () {
        if(this.verify.msg != 'ok'){
          Toast(this.verify.msg)
        }else{
          login({
            kind: Number(this.role),
            account: this.phone,
            captcha: this.captcha,
            password: this.password,
            once_str: this.loginBySms ? this.$refs.smsSend.once_str : '',
            openid: this.openid,
          }).then(res => {
            setSignIn({
              ...res.data,
              role: this.role,
              account: this.phone,
            })
            // 获取用户信息。强制刷新缓存。
            getUserData(true).finally(() => {
              this.afterLogin(res)
            })
          }).catch(err => {
            const {
              status,
              msg
            } = getErrInfo(err)
            setSignIn({
              account: this.phone
            })
            if(status == 401){
             this.afterLogin(err)
            }
            this.$refs.smsSend.resend = true
          })
        }
      },
      afterLogin(res){
        const {
          status,
          msg
        } = getErrInfo(res)
        if (this.isPopup) {
          this.$emit('afterLogin', res)
          return
        }
        let page = 'profile',
          params = {}
        // 供应商或者审核中的跳转
        if (this.role === '2' || status == 401) {
          page = 'registe/success'
          params.phone = this.phone
          if (this.role === '2') {
            params.role = 2
            params.state = 0
          }
        }
        this.getRedirect(page, params)
      },
    },
  }
</script>

<style lang="less" scoped>
  @import "~@style_m/basic/utils/index";
  .van-cell {
    padding-left: 0;
    padding-right: 0;
    font-size: 17px;
    margin: 13px 0;
    &:after, &:before {
       position: absolute;
        box-sizing: border-box;
        content: ' ';
        pointer-events: none;
        right: 0;
        bottom: 0;
        left: 0;
        border-bottom: 1px solid #ebedf0;
        transform: scaleY(1)
    }
    &:before {
      right: 100%;
      border-bottom-color: #444;
      transition: right ease .5s;
      z-index: 1;
    }
    &.active:before {
      right: 0;
    }
  }

  .van-button--default {
    border: none;
    border-left: 1px solid #f3f3f3;
    color: @color-main;
    &[disabled] {
        background: none!important;
        color: #ccc;
    }
  }
  .van-row--flex {
    color: #666;
    margin-top: 12.5px;
    font-size: 16px;
  }
  .van-button--small {
    height: 25px;
    line-height: 25px;
    border-radius: 0;
    font-size: @font-size-lg;
    padding-left: 15px;
    border-left-color: #e4e4e4;
  }
  a.van-button--disabled {
      color: #999!important;
      opacity: 1;
  }

</style>
